import * as THREE from "three";
import { loadFbx } from "./loadModel"
import { parseSlot } from "./slot"
import { getBox } from "./getBox";

export async function addBoards(data, { parentObj, deviceImgSize, deviceBox }) {
    // 解析板卡插槽
    let slots = []
    for (let slotData of data.slot) {
        let slot = parseSlot({
            angle: slotData.angle,
            imgPos: [slotData.pos.x, slotData.pos.y],
            imgSize: deviceImgSize,
            box: deviceBox,
        })
        slot.type = "BoardSlot"
        slot.userData = {
            id: slotData.id,
        }
        slots.push(slot)
        parentObj.add(slot)

        // // 坐标轴DEBUG
        // const axesHelper = new THREE.AxesHelper(1);
        // slot.add(axesHelper);
    }

    // 解析板卡
    for (let boardData of data.board) {
        let board = new THREE.Object3D()
        // 模型本身要旋转和偏移原点
        let model = await loadFbx(`model/board/${boardData.model_board}.FBX`)
        model.rotateX(Math.PI * 0.5) // 板卡默认是竖着的，变横
        // 横着时原点在左下角，变横后在右上角
        // 计算出尺寸后，将原点移到左上角去
        let modelBox = getBox(model)
        let size = modelBox.getSize(new THREE.Vector3())
        model.position.set(0, -size.y, -size.z)
        board.add(model)

        board.type = 'Board'
        board.userData = {
            id: boardData.id,
            slot: boardData.slot,
        }
        board.__3dd = {
            localBox: getBox(board),
        }

        let boardSlot = slots[boardData.slot_index]
        boardSlot.add(board)
    }
}

export function getBoards(root) {
    let objs = []
    root.traverse(obj => {
        if (obj.type === "Board") {
            objs.push(obj);
        }
    });
    return objs
}
